package com.zjuh.qss.web.common;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wint.help.biz.result.Result;
import wint.help.biz.result.ResultCode;
import wint.help.biz.result.ResultType;
import wint.help.biz.result.results.CommonResultCodes;
import wint.mvc.flow.FlowData;
import wint.mvc.form.Form;
import wint.mvc.template.Context;
import wint.mvc.view.types.json.JsonResult;

import com.zjuh.qss.biz.domain.TopicDO;

public class BaseAction {
	
	protected final Logger log = LoggerFactory.getLogger(getClass());
	
	protected Object result2Context(Result result, Context context, String name) {
		Object value = result.getModels().get(name);
		context.put(name, value);
		return value;
	}

	protected void result2Context(Result result, Context context) {
		for (Map.Entry<String, Object> entry : result.getModels().entrySet()) {
			context.put(entry.getKey(), entry.getValue());
		}
	}
	
	protected void handleError(Result result, FlowData flowData, Context context) {
		if (result.getResultType() == ResultType.COMMON_TARGET) {
			flowData.setTarget("error");
		}
		ResultCode resultCode = result.getResultCode();
		if (resultCode == null) {
			resultCode = CommonResultCodes.SYSTEM_ERROR;
		}
		context.put("resultCode", resultCode);
	}
	
	protected void handleJsonError(Result result, FlowData flowData, Context context) {
		flowData.setViewType("json");
		ResultCode resultCode = result.getResultCode();
		if (resultCode == null) {
			resultCode = CommonResultCodes.SYSTEM_ERROR;
		}
		context.put("result", result);
	}
	
	protected void handleJsonResult(Result result, FlowData flowData, Context context) {
		JsonResult jsonResult = new JsonResult(result);
		context.put("result", jsonResult);
		if (result.isSuccess()) {
			this.result2Context(result, context);
		} else {
			this.handleJsonError(result, flowData, context);
		}
	}
	
	protected void handleResult(Result result, FlowData flowData, Context context) {
		if (result.isSuccess()) {
			this.result2Context(result, context);
		} else {
			this.handleError(result, flowData, context);
		}
	}
	
	protected void hold(FlowData flowData, Result result, String formName, String objectName) {
		Form form = flowData.getForm(formName);
		TopicDO topic = (TopicDO)result.getModels().get(objectName);
		form.hold(topic);
	}
	
}
